package com.mycompany.config;



import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.config.AutowireCapableBeanFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.context.support.WebApplicationContextUtils;

import com.vaadin.data.fieldgroup.BeanFieldGroup;
import com.vaadin.ui.Component;
import com.vaadin.ui.DefaultFieldFactory;

public class Injector {
	 
    public static void inject(Component component) {
        inject(component, getApplicationContext());
    }
    
    public static void inject(DefaultFieldFactory fieldFactory) {
        inject(fieldFactory, getApplicationContext());
    }
    
    @SuppressWarnings("rawtypes")
	public static void inject(BeanFieldGroup beanFieldGroup) {
        inject(beanFieldGroup, getApplicationContext());
    }
 
    private static ApplicationContext getApplicationContext() {
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.currentRequestAttributes();
        HttpServletRequest request = requestAttributes.getRequest();
        HttpSession session = request.getSession(false);
        ApplicationContext applicationContext =  WebApplicationContextUtils.getRequiredWebApplicationContext(session.getServletContext());
        return applicationContext;
    }
 
    @SuppressWarnings("deprecation")
	private static void inject(Component component, ApplicationContext applicationContext) {
        AutowireCapableBeanFactory beanFactory = applicationContext.getAutowireCapableBeanFactory();
        beanFactory.autowireBeanProperties(component, AutowireCapableBeanFactory.AUTOWIRE_AUTODETECT, false);
    }
    
    @SuppressWarnings("deprecation")
	private static void inject(DefaultFieldFactory fieldFactory, ApplicationContext applicationContext) {
        AutowireCapableBeanFactory beanFactory = applicationContext.getAutowireCapableBeanFactory();
        beanFactory.autowireBeanProperties(fieldFactory, AutowireCapableBeanFactory.AUTOWIRE_AUTODETECT, false);
    }

    @SuppressWarnings({ "rawtypes", "deprecation" })
	private static void inject(BeanFieldGroup binder, ApplicationContext applicationContext) {
    	AutowireCapableBeanFactory beanFactory = applicationContext.getAutowireCapableBeanFactory();
    	beanFactory.autowireBeanProperties(binder, AutowireCapableBeanFactory.AUTOWIRE_AUTODETECT, false);

    }
}
